/*      $Id: mod_dir_index.c 1103 2010-12-02 03:09:21Z phrakt $    */
/*
 * Copyright (c) 2007 Jean-Francois Brousseau <phrakt@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/stat.h>

#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include <http/msg.h>
#include <http/http.h>
#include <http/entity.h>

#include <canopy/buf.h>
#include <canopy/log.h>

#include <httpd/httpd.h>


int   mod_dir_index_init     (void);
void  mod_dir_index_cleanup  (void);
int   mod_dir_index_handler  (struct httpd_hdlr_args *args);



static char *mod_dir_index_files[] = {
	"index.html",
	"index.htm",
};


#define FILE_TAB_SIZE	(sizeof(mod_dir_index_files) / sizeof(char *))


static int   mod_dir_index_setupenv (http_msg_t *);


/*
 * mod_dir_index_init()
 *
 * Setup the CGI environment.
 */
int
mod_dir_index_init(void)
{
	if (canopy_addhdlr(HTTPD_PHASE_URITRANS, HTTPD_HDLR_TAIL,
	    "mod_dir_index_handler", mod_dir_index_handler, NULL) == -1) {
		return (-1);
	}

	return (0);
}

/*
 * mod_dir_index_cleanup()
 *
 */
void
mod_dir_index_cleanup(void)
{

}

/*
 * mod_dir_index_handler()
 *
 * Main handler for CGI support
 */
int
mod_dir_index_handler(struct httpd_hdlr_args *args)
{
	int i, index, ret;
	char *newpath;
	const char *filename = NULL;
	DIR *dir;
	http_ent_t *entity;
	struct dirent *ent;
	struct stat st;
	http_msg_t *req = args->ha_req;
	http_msg_t *resp = args->ha_resp;

	/* we only work on directories */
	if (resp->msg_entity->ent_type != HTTP_ENT_DIR)
		return (HTTPD_HDLR_OK);

	cnp_log(httpd_logchan, CNP_LOG_DEBUG,
	    "opening directory %s for listing",
	    resp->msg_entity->ent_path);

	dir = opendir(resp->msg_entity->ent_path);
	if (dir == NULL) {
		cnp_log(httpd_logchan, CNP_LOG_ERRNO,
		    "failed to open directory %s for listing",
		    resp->msg_entity->ent_path);
		return (HTTPD_HDLR_ERR);
	}

	/*
	 * Read the directory's entries for matches against the filenames
	 * for index files.  When we do find a match, we first check whether
	 * a previous match was found on a filename with a smaller index.
	 * The filename with the smallest index wins.
	 */
	index = -1;

	while ((ent = readdir(dir)) != NULL) {
		if (ent->d_name[0] == '.')
			continue;

		for (i = 0; i < FILE_TAB_SIZE; i++) {
			if (strcmp(ent->d_name, mod_dir_index_files[i]) == 0) {
				if ((index == -1) || (index > i)) {
					index = i;
					filename = mod_dir_index_files[i];
				}
			}
		}

		/*
		 * If we match against the first entry, there's no chance
		 * we can find a better match, so break early
		 */
		if (index == 0)
			break;
	}

	closedir(dir);

	if (filename != NULL) {
		cnp_asprintf(&newpath, "%s/%s",
		    resp->msg_entity->ent_path, filename);
		if (newpath == NULL) {
			cnp_log(httpd_logchan, CNP_LOG_ERR,
			    "failed to allocate new entity path");
			return (HTTPD_HDLR_ERR);
		}

		stat(newpath, &st);

		cnp_log(httpd_logchan, CNP_LOG_DEBUG,
		    "changing request entity path from %s to %s",
		    resp->msg_entity->ent_path, newpath);

		resp->msg_entity->ent_path = newpath;
		resp->msg_entity->ent_type = HTTP_ENT_FILE;
		resp->msg_entity->ent_size = (uint64_t)st.st_size;
	}

	return (HTTPD_HDLR_OK);
}
